
package org.vectrics.mail;


import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import org.apache.log4j.Logger;
import org.vectrics.SystemException;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;


public class FreeMarkerManager {
	private Configuration freemarkerConfig = null;
	private Logger log = Logger.getLogger(this.getClass());

	
	public FreeMarkerManager(String templateDirectory) {
		super();
		freemarkerConfig = new Configuration();
		
		// Specify the data source where the template files come from.
		// Set a file directory for it:
		try {
			freemarkerConfig.setDirectoryForTemplateLoading(
			        new File(templateDirectory));
		} catch (Exception ex) {
			throw new SystemException("Exception setting", ex);
		}
		log.info("Configuration base dir: " + templateDirectory);		
	
		// Specify how templates will see the data model. This is an advanced topic...
		// but just use this:
		freemarkerConfig.setObjectWrapper(new DefaultObjectWrapper());  		
	}	

	
	/**
	 * FreeMarker is a 3rd Party library for creating text templates.
	 *
	 */
	public Template getTemplate(String fileName) throws IOException {
		Template freeMarkerTemplate = freemarkerConfig.getTemplate(fileName);
		return(freeMarkerTemplate);
	}
	
	public RecipientTemplateMergeResult processTemplate(Writer writer, String templateFileName, 
			Map<String, Object> parameters)  {
		RecipientTemplateMergeResult mergeResult = null;
		try {
			Template freeMarkerTemplate = this.getTemplate(templateFileName);
			TemplateMergeProcess processor = new TemplateMergeProcess(freeMarkerTemplate);			
			freemarkerConfig.setTemplateExceptionHandler(processor);
			log.info("Processing template against data object map");
			mergeResult = processor.process(writer, parameters);
	        writer.flush();
		} catch (Exception ex) {
			throw new SystemException("Exception processing template. fileName=" + templateFileName
					, ex);
		}
		return(mergeResult);
	}
	
}
